package com.btcode.orm.model.generater;

import com.btcode.db.executer.IDataExecuter;
import com.btcode.db.fieldtype.FieldType;
import com.btcode.db.result.Row;
import java.util.ArrayList;
import java.util.List;

public class SQLLetGenerater extends ModelGenerater {


    /**
     * @param executer
     */
    public SQLLetGenerater(IDataExecuter executer) {
        super(executer);
    }

    /* (non-Javadoc)
     * @see com.bandit.orm.model.generater.ModelGenerater#getTableInfoModels()
     */
    @Override
    public List<TableInfoModel> getTableInfoModels(String tableName) {

        String sql =
            " SELECT sql FROM sqlite_master WHERE type='table' AND name = '" + tableName + "'";

        List<Row> sqlResult = executer.queryList(sql, null);

        if (sqlResult.size() == 0) {
            throw new RuntimeException("表：" + tableName + "不存在");
        }

        String createTableSql = sqlResult.get(0).get("SQL").toString();
        createTableSql = createTableSql.split("\\(")[1].replaceAll("\\)", "");

        String[] columns = createTableSql.split(",");

        List<TableInfoModel> tableInfoModels = new ArrayList<>();

        for (int i = 0; i < columns.length; i++) {

            String column = columns[i].trim();
            String[] columnInfos = column.split(" ");

            TableInfoModel model = new TableInfoModel();
            model.setColumnName(columnInfos[0]);
            model.setDataType(columnInfos[1]);

            if (column.toUpperCase().indexOf("PRIMARY") > -1) {
                model.setIsKey("true");
            }

            tableInfoModels.add(model);
        }

        return tableInfoModels;
    }

    public FieldType getFieldEmunType(String type) {

        type = type.toLowerCase();

        if ("text".equals(type) || "character".equals(type)) {
            return FieldType.String;
        }
        else if ("datetime".equals(type)) {
            return FieldType.DateTime;
        }
        else if ("double".equals(type)) {
            return FieldType.Double;
        }
        else if ("int".equals(type)) {
            return FieldType.Integer;
        }
        else {
            return FieldType.String;
        }

    }

    public String getFieldJavaType(String type) {

        type = type.toLowerCase();

        if ("text".equals(type) || "character".equals(type)) {
            return "String";
        }
        else if ("datetime".equals(type)) {
            return "Date";
        }
        else if ("double".equals(type)) {
            return "Double";
        }
        else if ("int".equals(type)) {
            return "Integer";
        }
        else {
            return "String";
        }
    }

}
